<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ExhibitionTemplateResource;
use App\Models\ExhibitionCode;
use App\Services\ExhibitionCodeService;
use App\Services\ExhibitionSendMsgService;
use Illuminate\Http\Request;
use App\Models\ExhibitionName;
use App\Models\Arrived;
use App\Models\ExhibitionTemplate;
class ExhibitionController extends Controller
{
//    展示会议邀约时候的会议提示信息。富文本格式的
    public function show(){
        $exhibition = ExhibitionTemplate::first();
        return new ExhibitionTemplateResource($exhibition);
    }
    //展会签到
    public function store(Request $request)
    {
        //找出开放状态的展会
        $exhibition = ExhibitionName::where("is_open", true)->orderBy("id", "desc")->firstOrFail();
//        dd($exhibition);
//        dd(111);
        $arrived = $exhibition->arrived()->where("user_id",$request->user()->id)->first();

        $status = [
            "msg"=>"签到成功",
        ];
        //        没在邀约表里
        if (!$arrived){
            $data = [
                "user_id"=>$request->user()->id,
                "is_arrived"=>1,
                "exhibition_id"=>$exhibition->id,
                "arrive_time"=>time(),
            ];
            Arrived::create($data);
        }else{
            //还没签过到
            if ($arrived->is_arrived == 0){
                $arrived->is_arrived = 1;
                $arrived->arrive_time = time();
                $arrived->save();
            }else{
                $status['msg'] = "您已签到,无需重复签到";
            }
        }
        $request->user()->l_m = 1;
        $request->user()->save();
        return response()->json($status)->setStatusCode(200);
//        dd($arrived);

    }
//发送微信消息模版
    public function send_template_msg(ExhibitionSendMsgService $exhibitionSendMsgService){
        $exhibition = ExhibitionName::where("is_open",true)->first();
        if ($exhibition && $exhibition->weichatQueue()){
            $weichat = $exhibition->weichatQueue()->with("user")->get();
            //传入weichatQueue的Collection
            $exhibitionSendMsgService->sendMsg($weichat);
            return response(null);
        }else{
            abort(500,"无展会人员或者展会未开启");
        }

    }

    //获取展会签到二维码
    public function get_exhibition_code(ExhibitionCodeService $exhibitionCodeService)
    {
        $exhibitionCode = ExhibitionCode::firstOr(function () use($exhibitionCodeService){
           return $exhibitionCodeService->getExhibitionCode();
        });
        return response($exhibitionCode->img_url,200);
//        dd($exhibitionCode);
    }
}
